package com.future.service.impl;

import com.future.po.MonitorDevice;
import com.future.service.DeviceService;
import com.future.service.YSOpenService;
import com.future.utils.DateUtil;
import com.future.utils.FileUtil;
import com.future.utils.HttpUtil;
import com.future.utils.JacksonUtil;
import com.future.dto.YSOpenRequestInfoDto;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

/**
 * @author 86151
 */
@Service
public class YSOpenServiceImpl implements YSOpenService {

    @Resource
    private YSOpenRequestInfoDto ysOpenRequestInfoDto;

    @Resource
    private DeviceService deviceService;

    @Override
    public String getAccessToken() throws Exception {
        // 获取access_token的请求地址和请求参数
        String url = ysOpenRequestInfoDto.getGetURLOfAccessToken();
        String params = "appKey=" + ysOpenRequestInfoDto.getAppKeyOfYSOpen()
                + "&appSecret=" + ysOpenRequestInfoDto.getAppSecretOfYSOpen();
        String result = HttpUtil.post(url, params);

        // json
        String data = JacksonUtil.jsonNodeOf(result, "data", "accessToken").asText();
        // 每次获取新的token时，存入数据库
        MonitorDevice monitorDevice = new MonitorDevice();
        // 返回access_token
        return data;
    }

    @Override
    public File capture(String saveDir) throws Exception {
        String url = ysOpenRequestInfoDto.getURLOfCapture();
        String param1 = "accessToken=" + ysOpenRequestInfoDto.getAccessToken();
        String param2 = "&deviceSerial=" + ysOpenRequestInfoDto.getDeviceSerial()
                + "&channelNo=" + ysOpenRequestInfoDto.getChannelNo();

        String result = HttpUtil.post(url, param1 + param2);

        // 获取result失败
        int returnCode = JacksonUtil.jsonNodeOf(result, "code").asInt();
        if (returnCode == 10002) {
            // 重新获取accessToken
            ysOpenRequestInfoDto.setAccessToken(getAccessToken());
            param1 = "accessToken=" + ysOpenRequestInfoDto.getAccessToken();
            // 重新向萤石开放平台发送请求
            result = HttpUtil.post(url, param1 + param2);
        }

        String picUrl = JacksonUtil.jsonNodeOf(result, "data", "picUrl").asText();

        return FileUtil.receiveFile(picUrl, saveDir + "/" + DateUtil.toString(new Date()) + ".png");
    }
}
